package org.jeecg.modules.business.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.alibaba.api.IdentityVerify;
import org.jeecg.cmbCloudDirectLink.utils.GENKey;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.LimitSubmit;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.*;
import org.jeecg.modules.business.service.ICaishuiBusinessService;
import org.jeecg.modules.business.service.ICaishuiPreItemsService;
import org.jeecg.modules.business.service.ICaishuiServiceCompanyService;
import org.jeecg.modules.business.service.ISigningMemberService;
import org.jeecg.modules.manage.entity.CaishuiBusiness;
import org.jeecg.modules.manage.entity.CaishuiMember;
import org.jeecg.modules.manage.entity.CaishuiPreItems;
import org.jeecg.modules.manage.entity.CaishuiServiceCompany;
import org.jeecg.modules.manage.vo.SigningMemberImportVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
* @Description: 签约人才[B端]
* @Author: yfkj
* @Date:   2023-01-12
* @Version: V1.0
*/
@Api(tags="签约人才[B端]")
@RestController
@RequestMapping("/signingMemberB/signingMemberB")
@Slf4j
public class SigningMemberController extends JeecgController<CaishuiMember, ISigningMemberService> {

    @Autowired
    private ISigningMemberService signingMemberService;
    @Autowired
    private ICaishuiBusinessService iCaishuiBusinessService;
    @Autowired
    private ICaishuiServiceCompanyService iCaishuiServiceCompanyService;
    @Autowired
    private ICaishuiPreItemsService iCaishuiPreItemsService;
    @Autowired
    private ISysBaseAPI iSysBaseAPI;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;//文件上传根目录


   /**
    * 分页列表查询
    *
    * @param caishuiMember
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @ApiOperation(value="签约人才[B端]-分页列表查询", notes="签约人才-分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<CaishuiMember>> queryPageList(CaishuiMember caishuiMember,
                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                     HttpServletRequest req) {
       QueryWrapper<CaishuiMember> queryWrapper = QueryGenerator.initQueryWrapper(caishuiMember, req.getParameterMap());
       queryWrapper.lambda().eq(CaishuiMember::getBusinessId, TokenUtils.getLoginUser().getCurBusiness());
       queryWrapper.lambda().eq(CaishuiMember::getCompanyId, TokenUtils.getLoginUser().getCurCompany());
       Page<CaishuiMember> page = new Page<CaishuiMember>(pageNo, pageSize);
       IPage<CaishuiMember> pageList = signingMemberService.page(page, queryWrapper);
       return Result.OK(pageList);
   }

//    /**
//     *   添加
//     *
//     * @param caishuiMember
//     * @return
//     */
//    @AutoLog(value = "签约人才[B端]-添加", terminal = 2)
//    @ApiOperation(value="签约人才[B端]-添加", notes="签约人才[B端]-添加")
//    @PostMapping(value = "/add")
//    public Result<String> add(@RequestBody CaishuiMember caishuiMember) {
//        signingMemberService.save(caishuiMember);
//        return Result.OK("添加成功！");
//    }

    /**
     * 查询签约商户信息是否支持批量导入人才
     * @return
     */
    @ApiOperation(value = "签约人才[B端]-是否支持批量导入", notes = "签约人才[B端]-查询签约商户信息是否支持批量导入人才")
    @GetMapping(value = "/queryIsBatchImport")
    public Result queryIsBatchImport() {
        int batchImport = 0;
        //获取当前商户
        CaishuiBusiness business = iCaishuiBusinessService.getOne(new LambdaQueryWrapper<CaishuiBusiness>().select(CaishuiBusiness::getBatchImport)
                .eq(CaishuiBusiness::getId,TokenUtils.getLoginUser().getCurBusiness()));
        if(oConvertUtils.isNotEmpty(business)){
            batchImport = business.getBatchImport();
        }
        return Result.ok(batchImport);
    }


   /**
   * 导出excel
   *
   * @param request
   * @param caishuiMember
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, CaishuiMember caishuiMember) {
       caishuiMember.setBusinessId(TokenUtils.getLoginUser().getCurBusiness());
       caishuiMember.setCompanyId(TokenUtils.getLoginUser().getCurCompany());
       return super.exportXls(request, caishuiMember, CaishuiMember.class, "签约人才列表");
   }

    /**
     * 导入数据列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<List<SigningMemberImportVo>> importExcel(HttpServletRequest request) {
        List<SigningMemberImportVo> list = new ArrayList<>();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<SigningMemberImportVo> importVoList = ExcelImportUtil.importExcel(file.getInputStream(), SigningMemberImportVo.class, params);
                //按照编码长度排序
                Collections.sort(importVoList);
                list.addAll(importVoList);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("导入数据错误!");
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok(list);
    }

   /**
    * 处理导入人才数据
   *
   * @param jsonObject
   * @return
   */
    @AutoLog(value = "签约人才[B端]-批量导入人才数据", terminal = 2)
    @PostMapping(value = "/handleImportList")
    @LimitSubmit(key = "business:member:handleImportList:%bId:%cId")
    public Result<?> handleImportList(@RequestBody JSONObject jsonObject) throws IOException{
        Map<String, Object> result = new HashMap<>();
        Object signingService = jsonObject.get("signingService");//ID_name,ID_name 格式
        JSONArray jsonArray = jsonObject.getJSONArray("memberList");
        if(oConvertUtils.isEmpty(signingService) || oConvertUtils.listIsEmpty(jsonArray)){
            return Result.error("参数错误！");
        }

        //签约服务数据处理
        String signingServiceIds = "";
        String signingServiceNames = "";
        String[] services = signingService.toString().split(",");
        for (String ser : services) {
            signingServiceIds += ser.split("_")[0] + ",";
            signingServiceNames += ser.split("_")[1] + "、";
        }
        if(oConvertUtils.isEmpty(signingServiceIds) || oConvertUtils.isEmpty(signingServiceNames)){
            return Result.error("参数错误！");
        }else {
            signingServiceIds = signingServiceIds.substring(0, signingServiceIds.length() - 1);
            signingServiceNames = signingServiceNames.substring(0, signingServiceNames.length() - 1);
        }
        //商户信息
        CaishuiBusiness business = iCaishuiBusinessService.getById(TokenUtils.getLoginUser().getCurBusiness());
        if(oConvertUtils.isEmpty(business)){
            return Result.error("签约商户信息错误！");
        }
        //公司信息
        CaishuiServiceCompany company = iCaishuiServiceCompanyService.getById(TokenUtils.getLoginUser().getCurCompany());
        if(oConvertUtils.isEmpty(company)){
            return Result.error("服务公司信息错误！");
        }
        // 错误信息
        String errorMessage = "";
        int successLines = 0, errorLines = 0, repeatLines = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            //导入会员数据
            SigningMemberImportVo signingMember = JSONObject.parseObject(JSON.toJSON(jsonArray.get(i)).toString(), SigningMemberImportVo.class);
            if (oConvertUtils.isEmpty(signingMember)) {
                errorLines++;
                errorMessage += "第 " + (i + 1) + " 行：导入数据错误（为空或格式错误），已忽略导入。<br>";
                continue;
            }else if (oConvertUtils.isEmpty(signingMember.getCode())){
                signingMember.setCode(GENKey.genRandomString(new Random(), "0123456789", 8));
            }
            //判断数据是否为空
            if(oConvertUtils.isEmpty(signingMember.getName()) || oConvertUtils.isEmpty(signingMember.getPhone())
                    || oConvertUtils.isEmpty(signingMember.getIdCardType()) || oConvertUtils.isEmpty(signingMember.getIdCard())){
                errorLines++;
                errorMessage += "第 " + (i + 1) + " 行：导入数据错误（存在为空的字段），已忽略导入。<br>";
                continue;
            } else if (!CommonUtils.isValidMobile(signingMember.getPhone())) {//手机号码验证
                errorLines++;
                errorMessage += "第 " + (i + 1) + " 行：导入数据手机号码格式错误，已忽略导入。<br>";
                continue;
            }
            //身份证号码验证
            if(!IdcardValidator.isValidatedAllIdcard(signingMember.getIdCard())){
                errorLines++;
                errorMessage += "第 " + (i + 1) + " 行：身份证号码错误，已忽略导入。<br>";
                continue;
            }

            try {
                //判断该人才是否已存在（只需要判断身份证号码）
                long count = signingMemberService.count(QueryGenerator.initQueryWrapper(new CaishuiMember(),null).lambda()
                        .eq(CaishuiMember::getBusinessId,TokenUtils.getLoginUser().getCurBusiness())
                        .eq(CaishuiMember::getCompanyId,TokenUtils.getLoginUser().getCurCompany())
                        .eq(CaishuiMember::getIdCard,signingMember.getIdCard()));
                if(count > 0){
                    repeatLines++;
                    errorMessage += "第 " + (i + 1) + " 行：签约人才已存在，已忽略导入。<br>";
                    continue;
                }

                //信息比对
                if(signingMember.getIdCardType() == 1){ //身份证
                    //身份证二要素——阿里云市场
                    boolean bool = IdentityVerify.verify(signingMember.getName(), signingMember.getIdCard());
                    if (!bool) {
                        errorLines++;
                        errorMessage += "第 " + (i + 1) + " 行：姓名和身份证号码不匹配，已忽略导入。<br>";
                        continue;
                    }

                    //添加预充值记录
                    CaishuiPreItems preItems = new CaishuiPreItems();
                    preItems.setCreateBy(TokenUtils.getLoginUser().getUsername());
                    preItems.setCreateTime(new Date());
                    preItems.setCompanyId(TokenUtils.getLoginUser().getCurCompany());
                    preItems.setBusinessId(business.getId());
                    preItems.setTenantId(business.getTenantId());
                    preItems.setUserId(TokenUtils.getLoginUser().getId());
                    preItems.setPreType(2);
                    preItems.setPreRealname(signingMember.getName());
                    preItems.setPreIdCard(signingMember.getIdCard());
                    preItems.setPreNum(1);
                    double price = oConvertUtils.getDouble(iSysBaseAPI.queryValueByCode("A01A02"),0);
                    if (price <= 0) return Result.error("预充值未配置，请联系管理员！");
                    preItems.setPrePrice(price);
                    preItems.setPreAmount(price);
                    preItems.setPreStatus(1);
                    preItems.setPreRemarks("人才批量导入");
                    iCaishuiPreItemsService.save(preItems);
                }else {
                    errorLines++;
                    errorMessage += "第 " + (i + 1) + " 行：目前只支持身份证验证，已忽略导入。<br>";
                    continue;
                }

                //处理签约文件
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("companyName", company.getName());
                data.put("companyCode", company.getBusinessLicenseNo());
                data.put("name", signingMember.getName());
                data.put("idCard", signingMember.getIdCard());
                data.put("signService", signingServiceNames);
                data.put("businessName", business.getName());
                data.put("signDate", DateUtils.sdf.format(new Date()));
                String bizPath = "uploadImg/member/sign/" + business.getId();
                String fileName = "自由职业者服务协议_" + signingMember.getName() + "_" + signingMember.getIdCard() + "_" + RandomUtil.randomNumbers(5) + ".pdf";
                String path = upLoadPath + "/" + bizPath + "/" + fileName;
                boolean bool = PDFutils.pdfDataPaddingSign(data,path,fileName);
                if(!bool){
                    errorLines++;
                    errorMessage += "第 " + (i + 1) + " 行：生成签约文件错误，已忽略导入。<br>";
                    continue;
                }

                //文件上传
                String savePath = FileUploadUtil.fileUpload(path, bizPath + "/" + fileName);
                if(oConvertUtils.isEmpty(savePath)){
                    errorLines++;
                    errorMessage += "第 " + (i + 1) + " 行：上传签约文件错误，已忽略导入。<br>";
                    continue;
                }

                //处理签约人才实体类数据
                CaishuiMember caishuiMember = new CaishuiMember();
                BeanUtils.copyProperties(signingMember, caishuiMember);
                caishuiMember.setCompanyId(TokenUtils.getLoginUser().getCurCompany());
                caishuiMember.setBusinessId(business.getId());
                caishuiMember.setTenantId(business.getTenantId());
                caishuiMember.setSigningServiceId(signingServiceIds);
                caishuiMember.setSex(IdcardValidator.getSexFromIdCard(signingMember.getIdCard()));
                caishuiMember.setBirthday(IdcardValidator.getBirthDayFromIdCard(signingMember.getIdCard()));
                caishuiMember.setSigningType(2);
                caishuiMember.setSigningFile(savePath);//签约文件
                caishuiMember.setSigningStatus(2);
                signingMemberService.save(caishuiMember);
                successLines++;
            } catch (Exception e) {
                errorLines++;
                errorMessage += "第 " + (i + 1) + " 行：未知错误，已忽略导入。<br>";
                log.error(e.getMessage(), e);
            }
        }
        result.put("successLines",successLines);
        result.put("errorLines",errorLines);
        result.put("repeatLines",repeatLines);
        result.put("errorMessage",errorMessage);
        return Result.ok("操作成功！",result);
    }

}
